import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/business_card.dart';
import '../services/database_service.dart';
import '../widgets/business_card_item.dart';
import 'business_card_detail_screen.dart';
import 'camera_screen.dart';

class BusinessCardListScreen extends StatefulWidget {
  const BusinessCardListScreen({super.key});

  @override
  State<BusinessCardListScreen> createState() => _BusinessCardListScreenState();
}

class _BusinessCardListScreenState extends State<BusinessCardListScreen> {
  final DatabaseService _databaseService = DatabaseService();
  List<BusinessCard> _businessCards = [];
  List<BusinessCard> _filteredCards = [];
  bool _isLoading = true;
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _loadBusinessCards();
  }

  Future<void> _loadBusinessCards() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final cards = await _databaseService.getAllBusinessCards();
      setState(() {
        _businessCards = cards;
        _filteredCards = cards;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('载入名片失败: $e');
    }
  }

  void _searchCards(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredCards = _businessCards;
      } else {
        _filteredCards = _businessCards.where((card) {
          return card.name.toLowerCase().contains(query.toLowerCase()) ||
                 card.company.toLowerCase().contains(query.toLowerCase()) ||
                 card.position.toLowerCase().contains(query.toLowerCase()) ||
                 card.phone.contains(query) ||
                 card.email.toLowerCase().contains(query.toLowerCase());
        }).toList();
      }
    });
  }

  Future<void> _deleteBusinessCard(BusinessCard card) async {
    try {
      await _databaseService.deleteBusinessCard(card.id!);
      setState(() {
        _businessCards.remove(card);
        _filteredCards.remove(card);
      });
      _showSuccessSnackBar('名片已删除');
    } catch (e) {
      _showErrorSnackBar('删除名片失败: $e');
    }
  }

  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('名片全能王'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: BusinessCardSearchDelegate(_businessCards),
              );
            },
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.blue[50]!,
              Colors.white,
            ],
          ),
        ),
        child: _isLoading
            ? const Center(
                child: CircularProgressIndicator(),
              )
            : _filteredCards.isEmpty
                ? _buildEmptyState()
                : _buildCardList(),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          final result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const CameraScreen(),
            ),
          );
          if (result == true) {
            _loadBusinessCards();
          }
        },
        icon: const Icon(Icons.camera_alt),
        label: const Text('扫描名片'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.credit_card,
            size: 100,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 20),
          Text(
            _searchQuery.isEmpty ? '還沒有名片' : '沒有找到相關名片',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 10),
          Text(
            _searchQuery.isEmpty 
                ? '点击下方按钮开始扫描名片' 
                : '尝试其他关键词搜索',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCardList() {
    return RefreshIndicator(
      onRefresh: _loadBusinessCards,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _filteredCards.length,
        itemBuilder: (context, index) {
          final card = _filteredCards[index];
          return BusinessCardItem(
            card: card,
            onTap: () async {
              final result = await Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => BusinessCardDetailScreen(card: card),
                ),
              );
              if (result == true) {
                _loadBusinessCards();
              }
            },
            onDelete: () => _deleteBusinessCard(card),
          );
        },
      ),
    );
  }
}

class BusinessCardSearchDelegate extends SearchDelegate {
  final List<BusinessCard> cards;

  BusinessCardSearchDelegate(this.cards);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return _buildSearchResults();
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return _buildSearchResults();
  }

  Widget _buildSearchResults() {
    final filteredCards = cards.where((card) {
      return card.name.toLowerCase().contains(query.toLowerCase()) ||
             card.company.toLowerCase().contains(query.toLowerCase()) ||
             card.position.toLowerCase().contains(query.toLowerCase()) ||
             card.phone.contains(query) ||
             card.email.toLowerCase().contains(query.toLowerCase());
    }).toList();

    return ListView.builder(
      itemCount: filteredCards.length,
      itemBuilder: (context, index) {
        final card = filteredCards[index];
        return ListTile(
          leading: CircleAvatar(
            backgroundColor: Colors.blue[100],
            child: Text(
              card.name.isNotEmpty ? card.name[0].toUpperCase() : '?',
              style: TextStyle(
                color: Colors.blue[800],
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          title: Text(card.name),
          subtitle: Text(card.companyPosition),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => BusinessCardDetailScreen(card: card),
              ),
            );
          },
        );
      },
    );
  }
}
